package com.macro.mall.portal.util;

import com.macro.mall.portal.domain.vo.WxMsgVo;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateData;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class WxMsgPush {


    /**
     * 微信公众号API的Service
     */

    private final WxMpService wxMpService;


    /**
     * 构造注入
     *
     * @param
     */
    public WxMsgPush(WxMpService wxMpService) {
        this.wxMpService = wxMpService;
    }


    /**
     * 发送微信模板信息
     *
     * @param openId 接受者openId
     * @return 是否推送成功
     */
    public Boolean SendWxMsg(WxMsgVo vo) {
        // 发送模板消息接口
        WxMpTemplateMessage templateMessage = WxMpTemplateMessage.builder()
                // 接收者openid
                .toUser(vo.getOpenId())
                // 模板id
                .templateId(ConfigConstant.TEMPLATE_ID)
                // 模板跳转链接
                .url(vo.getUrl())
                .build();
        // 添加模板数据
        templateMessage.addData(new WxMpTemplateData("first", vo.getFirst(), "#FF00FF"))
                .addData(new WxMpTemplateData("keyword1", vo.getKeyword1(), "#c70024"))
                .addData(new WxMpTemplateData("keyword2", vo.getKeyword2(), "#000000"))
                .addData(new WxMpTemplateData("remark", vo.getRemark(), "#000000"));
        String msgId = null;
        try {
            // 发送模板消息
            msgId = wxMpService.getTemplateMsgService().sendTemplateMsg(templateMessage);
        } catch (WxErrorException e) {
            e.printStackTrace();
        }
        log.warn("·==++--·推送微信模板信息：{}·--++==·", msgId != null ? "成功" : "失败");
        return msgId != null;
    }
}
